package cn.pconline.autoclub.web.admin;

import cn.pconline.autoclub.entity.LoginHistory;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.PagerService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.Pager;
import com.alibaba.fastjson.JSONObject;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.SqlBuilder;
import org.gelivable.web.Env;
import org.gelivable.web.EnvUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author zhouruxuan
 * @date 2014年8月20日 下午2:27:57
 */
@Controller
@RequestMapping(value = "/admin")
public class LoginHistoryController {

	@Autowired
	private GeliDao geliDao;
	@Autowired
	private GeliOrm geliOrm;
	@Autowired
	private PagerService pagerService;
	@Autowired
	private UserService userService;
	
	private final String[] CLIENT_NAME = {"autoclub"};
	
	/**
	 * 显示查询结果
	 * @param req
	 * @param resp
	 */
	@RequestMapping(value = "/club/loginHistoryList.do")
	public String list (HttpServletRequest req, HttpServletResponse resp) {
		Env env = EnvUtils.getEnv();
		//param
		String userId = env.param("userId", "").trim();
		String loginDateFrom = env.param("loginDateFrom", "").trim();
		String loginDateTo = env.param("loginDateTo", "").trim();
		
        int pageNum = env.paramInt("pageNum", 1);
        int pageSize = env.paramInt("pageSize", 20);
        
        //sql
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select * from ").appendSql(geliOrm.getTableName(LoginHistory.class)).appendSql(" where 1=1 ");
        if (StringUtils.isEmpty(userId) == false) {
            sql.appendSql(" and userId = ").appendValue(userId);
        }
        if (StringUtils.isEmpty(loginDateFrom) == false) {
            sql.appendSql(" and login_datetime >= ").appendValue(loginDateFrom);
        }
        if (StringUtils.isEmpty(loginDateTo) == false) {
            sql.appendSql(" and login_datetime <=").appendValue(loginDateTo);
        }
        sql.appendSql(" order by login_datetime desc");

        //query
        Pager<LoginHistory> pager = pagerService.pager(LoginHistory.class, sql, pageNum, pageSize);

        //return
        req.setAttribute("pager", pager);
        req.setAttribute("userId", userId);
        req.setAttribute("loginDateFrom", loginDateFrom);
        req.setAttribute("loginDateTo", loginDateTo);

        return "admin/club/loginHistoryList";
	}
	
	/**
	 * 记录用户登录时间接口
	 * @param req
	 * @param resp
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/club/saveLoginInfo.do", method = RequestMethod.GET)
	public JSONObject saveLoginInfo(HttpServletRequest req, HttpServletResponse resp) {
		//param
		Env env = EnvUtils.getEnv();
		String userId = env.param("userId");
		String client = env.param("client");
		
		//return message
		JSONObject jsonObject = new JSONObject();
		int code;
		String returnMessage;
		
		//validate rules
		if(!StringUtils.isNumeric(userId)) {
			code = 1;
			returnMessage = "用户ID不能为空，且必需是由数字组成";
		} else if(!isValidUser(Long.parseLong(userId))) {
			code = 2;
			returnMessage = "用户ID不存在";
		} else if(StringUtils.isEmpty(client)) {
			code = 3;
			returnMessage = "调用终端不能为空";
		} else if(!isValidClient(client)) {
			code = 4;
			returnMessage = "调用终端值不正确";
		} else {
			LoginHistory loginHistory = new LoginHistory();
			loginHistory.setUserId(Long.parseLong(userId));
			loginHistory.setClient(client);
			loginHistory.setLoginDateTime(new Date());
			geliDao.create(loginHistory);
			
			code = 0;
			returnMessage = "成功记录用户登录信息";
		}
		
		//return
		jsonObject.put("code", code);
		jsonObject.put("message", returnMessage);
		
		return jsonObject;
	}
	
	/**
	 * 判断用户ID是否在车友会用户中存在
	 * @param userId
	 * @return
	 */
	public boolean isValidUser(long userId) {
		User user = userService.findUser(userId);
		if(user == null) {
			return false;
		}
		return true;
	}
	
	/**
	 * 判断调用终端的值是否正确
	 * @param client
	 * @return
	 */
	public boolean isValidClient(String client) {
		boolean flag = false;
		for(String str : CLIENT_NAME) {
			if(client.equals(str)) {
				flag = true;
			}
		}
		return flag;
	}
	
}
